import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/pages/whl_home/whl_publish/push_top_setting/push_top_setting_sheet.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../model/base_model.dart';
import '../../model/dynamic_model.dart';
import '../../model/topic_model.dart';
import '../../network/whl_api.dart';
import '../../routes/whl_app_pages.dart';
import 'comment/comment_view.dart';

class SquareLogic extends GetxController with GetTickerProviderStateMixin {
  String? adCode;
  List<BaseModel> naviList = [
    BaseModel(title: '广场'),
    BaseModel(title: '短视频'),
    // BaseModel(title: '直播'),
  ];
  List<BaseModel> tabList = [
    BaseModel(
        id: '1',
        title: '热门',
        refreshController: EasyRefreshController(
            controlFinishLoad: true, controlFinishRefresh: true)),
    BaseModel(
        id: '2',
        title: '最新',
        refreshController: EasyRefreshController(
            controlFinishLoad: true, controlFinishRefresh: true)),
    BaseModel(
        id: '3',
        title: '同城',
        refreshController: EasyRefreshController(
            controlFinishLoad: true, controlFinishRefresh: true)),
    BaseModel(
        id: '4',
        title: '话题',
        refreshController: EasyRefreshController(
            controlFinishLoad: true, controlFinishRefresh: true)),
    BaseModel(
        id: '5',
        title: '我的关注',
        refreshController: EasyRefreshController(
            controlFinishLoad: true, controlFinishRefresh: true)),
  ];

  late BaseModel selectedSubTab;
  late TabController tabController;
  late TabController subTabController;
  List listData = [];
  int size = 10;
  int current = 1;

  List topicList = [];
  List oneTopicList = [];
  List twoTopicList = [];
  TopicModel? selectTopicModel;

  late AMapFlutterLocation flutterLocation;

  @override
  void onInit() {
    super.onInit();
    flutterLocation = AMapFlutterLocation();
    selectedSubTab = tabList[0];
    tabController = TabController(length: naviList.length, vsync: this);

    subTabController = TabController(length: tabList.length, vsync: this)
      ..addListener(() {
        if (tabList[subTabController.index].id == '3') {
          WhlPermissionUtil.reqLocationWhenInUsePermission(onSuccessAction: () {
            flutterLocation.startLocation();
          });
        } else {
          selectTypeChang(tabList[subTabController.index]);
        }
      });
    // // flutterLocation.
    // flutterLocation.startLocation();
    flutterLocation.onLocationChanged().listen((event) {
      adCode = event["adCode"].toString();
      selectTypeChang(tabList[subTabController.index]);
      String cityCode = event["cityCode"].toString();
      if (cityCode != '') {
        flutterLocation.stopLocation();
      }
    });
    loadSquareData(selectedSubTab, isRefresh: true);
    loadTopicData();
  }

  loadSquareData(BaseModel model, {bool isRefresh = false}) async {
    if (isRefresh) {
      current = 1;
    } else {
      current++;
    }
    Map<String, dynamic> param = {
      "size": size,
      "current": current,
      "type": model.id,
      "adCode": adCode,
    };
    if (model.id == '3' && adCode?.isEmpty == true) {
      model.data = [];
      model.refreshController?.finishRefresh();
      model.refreshController?.resetFooter();
      update();
      return;
    }
    if (model.id == '4') {
      param["talkId"] = selectTopicModel?.id;
    }
    // BaseModel model = tabList[selectedTabIndex];
    ResponseData responseData = await WhlApi.getSquareList.get(param);
    if (responseData.isSuccess()) {
      List records = responseData.data["records"];
      List<DynamicModel> modelList =
          records.map((e) => DynamicModel.fromJson(e)).toList();
      // modelList[0].topOrder = 4;
      // modelList[0].hot = 1;
      if (isRefresh) {
        model.data = modelList;
        model.refreshController?.finishRefresh();
        model.refreshController?.resetFooter();
      } else {
        model.data?.addAll(modelList);
        model.refreshController?.finishLoad();
      }
      if (records.length < size) {
        model.refreshController?.finishLoad(IndicatorResult.noMore);
      }
      update();
    } else {
      current--;
      model.refreshController?.finishRefresh();
      model.refreshController?.finishLoad();
      update();
    }
  }

  loadTopicData() {
    WhlApi.getTopicList.get({}, withLoading: true).then((value) {
      if (value.isSuccess()) {
        topicList = value.data.map((e) => TopicModel.fromJson(e)).toList();
        if (topicList.length < 2) {
          oneTopicList = topicList;
        } else {
          int index = topicList.length ~/ 2;
          if (topicList.length % 2 != 0) {
            index += 1;
          }
          oneTopicList = topicList.sublist(0, index);
          twoTopicList = topicList.sublist(index);
        }
        update();
      }
    });
  }

  void selectTypeChang(BaseModel model) {
    if (selectedSubTab.id == model.id) return;
    selectedSubTab = model;
    update();
    if ((model.data ?? []).isEmpty) {
      loadSquareData(model, isRefresh: true);
    }
  }

  Future<void> toSendPage() async {
    var a = await Get.toNamed(Routes.publish);
    if (a != null) {
      BaseModel model = selectedSubTab;
      loadSquareData(model, isRefresh: true);
      // model.refreshController?.callRefresh();
    }
  }

  void topicItemAction(TopicModel model) {
    if (selectTopicModel?.id == model.id) {
      selectTopicModel = null;
    } else {
      selectTopicModel = model;
    }
    update();
    loadSquareData(selectedSubTab, isRefresh: true);
  }

  void pushTopSetting(DynamicModel model) {
    Get.bottomSheet(
      PushTopSettingSheet(
        id: model.id,
        dataSource: DynamicDataSource.Square,
      ),
      isScrollControlled: true,
    ).then((value) {
      // model
      print(value);
    });
  }

  Future<void> toEditSquarePage(DynamicModel model) async {
    var a = await Get.toNamed(Routes.publish, arguments: {"model": model});
    if (a != null) {
      BaseModel model = selectedSubTab;
      model.refreshController?.callRefresh();
    }
  }
}
